package cn.xd.base.controller.admin;

import cn.hutool.core.util.ObjUtil;
import cn.xd.base.application.dto.cmd.CheckOrgNameDTO;
import cn.xd.base.application.dto.query.AdminOrgQuery;
import cn.xd.base.application.service.command.AdminOrgAppService;
import cn.xd.base.application.service.query.AdminOrgQueryAppService;
import cn.xd.base.domain.bean.command.AddAdminOrgCommand;
import cn.xd.base.domain.bean.command.UpdateAdminOrgCommand;
import cn.xd.base.domain.bean.response.AdminOrgDTO;
import cn.xd.base.domain.bean.response.JsonAdminOrgTree;
import cn.xd.common.response.ResponseResult;
import cn.xd.web.utils.SecurityUtils;
import com.google.common.collect.Lists;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 机构管理（adminOrg）
 *
 * @author mirzalin
 */
@RestController
@RequestMapping("/admin/org")
public class AdminOrgController {
    @Resource
    private AdminOrgAppService adminOrgAppService;
    @Resource
    private AdminOrgQueryAppService adminOrgQueryAppService;

    /**
     * 新增
     *
     * @param command
     * @return
     */
    @PostMapping("/add")
    public ResponseResult<AdminOrgDTO> add(@Valid @RequestBody AddAdminOrgCommand command) {
        return ResponseResult.success(adminOrgAppService.addAdminOrg(command, SecurityUtils.getUserId()));
    }


    /**
     * 更新
     *
     * @param command
     * @return
     */
    @PostMapping("/update")
    public ResponseResult<AdminOrgDTO> update(@Valid @RequestBody UpdateAdminOrgCommand command) {
        return ResponseResult.success(adminOrgAppService.updateAdminOrg(command, SecurityUtils.getUserId()));
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @PostMapping("/delete/{id}")
    public ResponseResult<?> delete(@PathVariable Long id) {
        adminOrgAppService.deleteAdminOrg(id);
        return ResponseResult.success();
    }


    /**
     * 查询机构（tree）
     *
     * @param query
     * @return
     */
    @PostMapping("/getAdminOrgJsonTree")
    public ResponseResult<List<JsonAdminOrgTree>> getAdminOrgJsonTree(@RequestBody AdminOrgQuery query) {
        if (ObjUtil.isEmpty(SecurityUtils.getAdminUserOrgId())) {
            return ResponseResult.success(new ArrayList<>());
        }
        return ResponseResult.success(Lists.newArrayList(adminOrgQueryAppService.getAdminOrgJsonTree(SecurityUtils.getAdminUserOrgId())));
    }

    /**
     * 检查机构名称是否存在
     *
     * @return
     */
    @PostMapping("/checkHasName")
    public ResponseResult<Boolean> checkHasName(@Validated @RequestBody CheckOrgNameDTO dto) {
        return ResponseResult.success(adminOrgQueryAppService.checkHasName(dto.getName(), dto.getParentId(), dto.getId()));
    }

}
